package top.zhangjianyong;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import top.zhangjianyong.entity.Log;
import top.zhangjianyong.utils.IdWorker;
import top.zhangjianyong.utils.RegexUtil;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 本地统计
 *
 * @author zhangjianyong
 * @since 2024/7/23 上午9:52
 */
@Slf4j
public class LocalAnalyzeLog {
    private final static String regex = "^(\\S*) - (\\S*) \\[([\\S\\s]*)] \"([^\"]*)\" ([0-9]*) ([0-9]*) \"([^\"]*)\" \"([^\"]*)\"";
    private final static IdWorker idWorker = new IdWorker(1, 1, 1);

    private final static Map<String, AtomicInteger> map = new ConcurrentHashMap<>();


    public static void main(String[] args) {
        String logPath = "/Users/zhangjianyong/Downloads/access_proxy.log";
        //logPath = args[0];
        InputStream ins = null;
        BufferedReader br = null;
        AtomicInteger atomicInteger = new AtomicInteger(0);
        try {
            ins = new FileInputStream(logPath);
            br = new BufferedReader(new InputStreamReader(ins));
            br.lines().parallel()
                    .filter(StrUtil::isNotBlank)
                    .map(line -> {
                        //log.info(line);
                        return RegexUtil.matchesAll(line, regex);
                    })
                    .map(list -> new Log(list, idWorker.nextId()))
                    .forEach(l -> {
                        String remoteAddr = l.getRemoteAddr();
                        map.computeIfAbsent(remoteAddr, k -> new AtomicInteger()).incrementAndGet();
                        int i = atomicInteger.incrementAndGet();
                        log.info("{}", i);
                    });


        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } finally {
            IoUtil.close(ins);
            IoUtil.close(br);
        }
    }
}
